package com.enzoism.springboot.dive.chapter02;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * whenComplete  完成时 触发的事件  supplyAsync、whenComplete使用的都是deamon线程，主线程退出后，进程退出，导致结果没有打印
 * @link https://blog.csdn.net/qq_40826106/article/details/88628536
 */
public class ComletableDemo {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        ComletableDemo demo = new ComletableDemo();
        IntStream.range(0, 5).forEach(value -> {
            CompletableFuture.supplyAsync(() -> {
                return demo.do3Second();
            }).whenComplete((resultStr, throwable) -> {
                System.out.println(resultStr + "-耗时：" + (System.currentTimeMillis() - start));
            });
            CompletableFuture.supplyAsync(() -> {
                return demo.do5Second();
            }).whenComplete((resultStr, throwable) -> {
                System.out.println(resultStr + "-耗时：" + (System.currentTimeMillis() - start));
            });
        });

        System.out.println("我没有被阻塞住");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("任务执行完成，JVM退出程序");
        }));
        // Thread.sleep (1000000L);
    }

    //任务一
    public String do3Second() {
        try {
            System.out.println("正在执行3秒的方法");
            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "##3";
    }

    //任务二
    public String do5Second() {
        try {
            System.out.println("正在执行5秒的方法");
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "##5";
    }
    //supplyAsync  默认使用的是守护线程，所以当执行到main线程后，已经没有非守护线程了，此时任务还没执行完成，所以要指定线程池


}